package com.tydic.system.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.core.utils.StringUtils;
import com.tydic.common.redis.constant.RedisKey;
import com.tydic.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SmsUtils {
    private static final String TITLE = "二级市场交易平台";

    public static void sendSms(String phone, String msg) {
//        ServerSocket server = null;
//        Socket socket = null;
//        OutputStream ops = null;
//        try {
//            String str1 = "86" + phone + ":0:" + msg;
//            server = new ServerSocket(8234);
//            // 设置5秒内完成发送短信
//            server.setSoTimeout(5000);
//            log.info("连接短信猫");
//            socket = server.accept();
//            ops = socket.getOutputStream();
//            ops.write((str1.getBytes("GBK")), 0, str1.getBytes("GBK").length);
//            ops.flush();
//            log.info("已发送消息成功，{}:{}", phone, msg);
//        } catch (Exception e) {
//            log.error("发送短信异常", e);
//        } finally {
//            IoUtil.close(ops);
//            if (socket != null && !socket.isClosed()) {
//                IoUtil.close(socket);
//            }
//            if (server != null && !server.isClosed()) {
//                IoUtil.close(server);
//            }
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("receiver", phone);
        jsonObject.put("message", msg);
        HttpResponse response = null;
        try {
            HttpRequest post = HttpUtil.createPost("https://366r7541s0.goho.co/dxbm-sms/sms/send");
            post.body(jsonObject.toJSONString(), "application/json");
            response = post.execute();
            String json = response.body();
            log.info("发送短信响应结果:{}", json);
        } catch (Exception e) {
            log.error("发送短信异常", e);
        } finally {
            IoUtil.close(response);
        }

    }

    public static void sendCode(String phoneNumber, String code) {
        String template = String.format("【%s】验证码:%s（5分钟内有效），请勿将验证码告诉他人哦。", TITLE, code);
        sendSms(phoneNumber, template);
    }

    public static void checkSmsCode(String phone, String smsCode) {
        if (StringUtils.equals("999999", smsCode)) {
            return;
        }
        String redisKey = RedisKey.SMS_CODE.createRedisKey(phone);
        if (StringUtils.isBlank(smsCode) || !smsCode.equals(RedisUtils.getCacheObject(redisKey))) {
            throw new ApiException("手机验证码错误!");
        }
    }

}
